/*
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fs from "node:fs";
import path from "node:path";

// 创建文件
const createDir = function (paths) {
  if (fs.existsSync(paths)) {
    return true;
  } else {
    if (createDir(path.dirname(paths))) {
      fs.mkdirSync(paths);
      return true;
    }
  }
};

const makeFile = (out, item = []) => {
  let name = getFileName(out);
  createDir(name.outPath);
  const json = [...item];
  let fileRes = path.resolve(name.outPath, name.outName);
  if (fs.existsSync(fileRes)) {
    fs.unlinkSync(fileRes);
  }
  console.log("All parse completed, writing in progress");
  fs.writeFileSync(fileRes, JSON.stringify(json, null, "  "));
};

// 解析文件名
const getFileName = (url) => {
  const u = url.replace(/\\/g, "/");
  let fileIndex = u.lastIndexOf("/");
  const fileName = fileIndex > 0 ? u.substr(fileIndex + 1) : "default.json";
  const outPath = u.substr(0, fileIndex);
  return {
    outName: fileName,
    outPath: outPath,
  };
};

const validFileExist = (file) => {
  if (!fs.existsSync(path.resolve(file))) {
    console.log(`Error: no such file or directory, open ${path.resolve(file)}`);
    console.log(` --- Next task Continue. `);
    return false;
  }
  return true;
};

const isAllRule = (rule = "") => {
  return rule.toLowerCase() === "all";
};

const getNodeList = (node) => {
  const result = [];
  let curNode = node;
  while (true) {
    result.push({
      kind: curNode.kind,
      name: curNode?.name?.escapedText,
    });
    if (curNode?.parent) {
      curNode = curNode.parent;
    } else {
      break;
    }
  }
  return result;
};

export { makeFile, getFileName, validFileExist, isAllRule, getNodeList };
